import { treeSource } from '@/services/api/api-publicity-source';
import {
  CloseOutlined,
  FolderOutlined,
  FrownFilled,
  FrownOutlined,
  HomeOutlined,
  TagOutlined,
} from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { Button, Descriptions, Empty, Space, Spin } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { useState } from 'react';
import { useAccess } from 'umi';
import AddSource from './AddSource';
import EditSource from './EditSource';
import DescriptionsItem from 'antd/lib/descriptions/Item';
import e from 'express';

interface DetailsSourceProps {
  onRefurbish: () => void;
}

const DetailsSource: React.FC<DetailsSourceProps> = ({ id, name, onRefurbish }) => {
  const access = useAccess();

  /**
   * 初始化树形数据
   */
  const [dataTree, setDataTreeState] = useState<DataNode[]>();

  /**
   * 树形列表选择数据
   */
  const [selectNode, setSelectNodeState] = useState<any>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: PublicitySourceData.Source[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          children: readyTreeData(val.children as PublicitySourceData.Source[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <TagOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadSourceData = async () => {
    try {
      const response = await treeSource();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setDataTreeState(treeData);
      }
    } catch (error) { }
  };

  return (
    <DrawerForm
      key="publicity_details_source_drawer_form"
      title="来源配置"
      drawerProps={{
        destroyOnClose: true,
      }}
      trigger={<Button>来源配置</Button>}
      onVisibleChange={(visible) => {
        if (visible) {
          loadSourceData();
        } else {
          setSelectNodeState(undefined);
        }
      }}
      submitter={false}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={false}
      >
        {selectNode?.selected && (
          <Space wrap>
            {selectNode?.node?.pos.length > 4 && (
              <EditSource
                data={selectNode.node.item}
                onRefurbish={() => {
                  loadSourceData();
                  onRefurbish();
                  setSelectNodeState(undefined);
                }}
              />
            )}
            {selectNode?.node?.pos.length > 2 && selectNode?.node?.item?.score === null && (
              <AddSource
                parent={selectNode.node.item}
                onRefurbish={() => {
                  loadSourceData();
                  onRefurbish();
                }}
              />
            )}
            {/* <Button
              type="primary"
              danger
              disabled={selectNode?.node?.pos.length <= 4}
              onClick={() => {
                // Modal.confirm({
                //   title: '是否要删除该权限',
                //   icon: <ExclamationCircleOutlined />,
                //   okText: '是',
                //   okType: 'danger',
                //   cancelText: '否',
                //   async onOk() {
                //     try {
                //       const response = await deleteSource({ id: selectNode?.node?.key });
                //       if (response.code === 0) {
                //         message.success('提交成功');
                //         loadSourceData();
                //         onSelect({});
                //         setSelectNodeState({});
                //         onRefurbish();
                //       }
                //     } catch (error) {
                //       message.success('提交失败');
                //     }
                //   },
                //   onCancel() {},
                // });
              }}
            >
              删除
            </Button> */}
          </Space>
        )}
        {dataTree && dataTree.length ? (
          <Tree
            defaultExpandAll
            height={800}
            showLine={{ showLeafIcon: false }}
            showIcon={true}
            treeData={dataTree}
            onSelect={(selectedKeys: React.Key[], info: any) => {
              console.log('==========', info);
              setSelectNodeState(info);
            }}
          />
        ) : (
          <Empty />
        )}
        {selectNode?.selected && (
          <Descriptions
            title="基本信息"
            bordered
            style={{
              marginTop: '10px',
            }}
          >
            <Descriptions.Item label="上级" span={2}>
              {selectNode?.node.item.parentName}
            </Descriptions.Item>
            <Descriptions.Item label="排序">{selectNode?.node.item.seq}</Descriptions.Item>
            <Descriptions.Item label="名称" span={2}>
              {selectNode?.node.item.name}
            </Descriptions.Item>
            <Descriptions.Item label="得分">{selectNode?.node.item.score}</Descriptions.Item>
            <Descriptions.Item label="描述" span={3}>
              {selectNode?.node.item.describes}
            </Descriptions.Item>
            <Descriptions.Item label="文件夹">
              {selectNode?.node.item.isFolder == 1 ? '是' : '否'}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {selectNode?.node.item.state == 1 ? '启用' : '禁用'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsSource;
